package com.yh.tea.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yh.tea.entity.ArticleType;
import com.yh.tea.entity.User;
import com.yh.tea.mapper.ArticleTypeMapper;
import com.yh.tea.model.ArticleTypeQuery;
import com.yh.tea.model.ArticleTypeVO;
import com.yh.tea.model.PageDTO;
import com.yh.tea.model.UserVO;
import com.yh.tea.service.ArticleTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yh.tea.utiity.ResponseResult;
import jdk.management.resource.ResourceRequest;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author yh
 * @since 2024-04-08
 */
@Service
public class ArticleTypeServiceImpl extends ServiceImpl<ArticleTypeMapper, ArticleType> implements ArticleTypeService {

    @Override
    public ResponseResult getPage(ArticleTypeQuery articleTypeQuery) {
        Page<ArticleType> page= Page.of(articleTypeQuery.getPageNo(),articleTypeQuery.getPageSize());

        // 1.2.排序条件
        if(articleTypeQuery.getSortBy().isEmpty()){
            // 如果排序字段为空，按照更新时间排序
            page.addOrder(new OrderItem("add_time", false));
        } else {
            page.addOrder(new OrderItem(articleTypeQuery.getSortBy(), articleTypeQuery.getIsAsc()));
        }

        //模糊查询寻
        if(articleTypeQuery.getArticleTypeName().isEmpty()){
            this.page(page);

        }else {
            this.page(page,new QueryWrapper<ArticleType>().like("type_name",articleTypeQuery.getArticleTypeName()));
        }

        List<ArticleType> articleTypeList=page.getRecords();

        if(articleTypeList == null || articleTypeList.isEmpty()){
            return ResponseResult.success("",new PageDTO<ArticleTypeVO>(page.getPages(),page.getTotal(),new ArrayList()));
        }

        // 4. 存在数据，进行实体类转换
        List<ArticleTypeVO> articleTypeVOList=new ArrayList();
        for (ArticleType articleType : articleTypeList) {
            articleTypeVOList.add(new ArticleTypeVO(articleType.getTypeName()));
        }
        // 5. 封装返回结果
        return ResponseResult.success("",new PageDTO<ArticleTypeVO>(page.getTotal(),page.getPages(),articleTypeVOList));
    }
}
